import re,datetime,codecs
import pandas as pd



def ReadFile(filePath):
    with codecs.open(filePath, "r") as f:
        return f.read()
def WriteFile(filePath, u, encoding="utf-8"):
    # with codecs.open(filePath,"w",encoding) as f:
    with codecs.open(filePath, "wb") as f:
        f.write(u.encode(encoding, errors="ignore"))
def CSV_2_UTF8(src, dst):
    content = ReadFile(src)
    WriteFile(dst, content, encoding="utf-8")


#  指定目录下，将数据带时间后缀保存为csv格式
def saveCsvByTime(OQPath,fileNanme,saveData,TimeFlag):
    # OQPath:导出目录，fileNanme：文件名前缀，saveData：保存的数据
    now = datetime.datetime.now()
    if TimeFlag==True:
        filename = f"{fileNanme}_{now.strftime('%Y-%m-%d_%H-%M-%S')}.csv"
    else:
        filename = f"{fileNanme}.csv"
    full_path = OQPath + "\\" + filename
    saveData.to_csv(full_path,index=False)


CSV_2_UTF8(r'C:\Users\AXZQ\Desktop\AUTO\ETFUpdate\etf.csv', r'C:\Users\AXZQ\Desktop\AUTO\ETFUpdate\etf_utf8.csv')
oaData=pd.read_csv(r'C:\Users\AXZQ\Desktop\AUTO\ETFUpdate\etf_utf8.csv')
oaDataNew=oaData[(oaData['主题'].str.contains('设置申赎资格'))]
etfTitle=oaDataNew['主题'].str.replace('请为','')
my_list = etfTitle.tolist()
CalldataNew=pd.DataFrame()
for title in my_list:
    keywords = re.findall(r'\w+', title)
    print(keywords)
    CallDataList=[]
    if len(keywords) ==7:
        CallDataList.append(keywords[0][:-4])
        CallDataList.append(keywords[0][-4:]+'-'+keywords[1]+'-'+keywords[2])
        CallDataList.append(keywords[3])
        CallDataList.append(keywords[4])
        Calldata=pd.DataFrame(CallDataList).T
        # print(Calldata)
        CalldataNew=pd.concat([CalldataNew,Calldata])
    elif len(keywords) ==5:
        CallDataList.append(keywords[0])
        CallDataList.append(None)
        CallDataList.append(keywords[1])
        CallDataList.append(keywords[2])
        Calldata=pd.DataFrame(CallDataList).T
        CalldataNew=pd.concat([CalldataNew,Calldata])
    elif len(keywords) ==8:
        CallDataList.append(keywords[0][:-4])
        CallDataList.append(keywords[0][-4:]+'-'+keywords[1]+'-'+keywords[2])
        CallDataList.append(keywords[3])
        CallDataList.append(keywords[5])
        Calldata=pd.DataFrame(CallDataList).T
        CalldataNew=pd.concat([CalldataNew,Calldata])
etfPath='C:\\Users\\AXZQ\\Desktop\\AUTO\\ETFUpdate'
CalldataNew = CalldataNew.rename(columns={0:"上市类型",1:"上市时间",2:"ETF名称",3:"ETF代码"})
CalldataNew.sort_values(by='上市时间',inplace=True,ascending=True)
# print(CalldataNew)
# saveCsvByTime(etfPath,'etfCall',CalldataNew,True)
with open('C:\\Users\\AXZQ\\Desktop\\AUTO\\ETFUpdate\\dist\\ETFUpdate.txt', 'w') as f:
    today = datetime.date.today()
    f.write(f'{today}-安信可申赎未上市ETF清单\n')
    f.write(f'尊敬的客户，您好！\n')
    f.write(f'   截止至{today}，共有{CalldataNew.shape[0]}只ETF安信已申请申赎资格但ETF套利系统仍未添加白名单。可在上市前1日，于下午4点半之后在网厅签署ETF风险揭示书；上市首日可在ETF套利系统ETF清单查找到对应ETF\n')
    for i in range(CalldataNew.shape[0]):
        f.write(f'{i+1}、{CalldataNew["上市类型"].iloc[i]} {CalldataNew["上市时间"].iloc[i]} ,{CalldataNew["ETF名称"].iloc[i]} ({CalldataNew["ETF代码"].iloc[i]}) \n')

    listDate=list(set(CalldataNew["上市时间"].tolist()))
    # while None in listDate:
    #     listDate.remove(None)
    # print(listDate)
    # listDate=listDate.sort()
    # print(listDate)

    for j  in listDate:
        weixinData=CalldataNew[CalldataNew["上市时间"]==j]
        # print(weixinData)
        # print('---------')
        f.write(f'【ETF套利】尊敬的客户您好，新增')
        for i in range(weixinData.shape[0]):
            f.write(f'（{weixinData["上市类型"].iloc[i]} {weixinData["上市时间"].iloc[i]}) {weixinData["ETF名称"].iloc[i]} ({weixinData["ETF代码"].iloc[i]})、')
        f.write(f'申赎资格，请在操作前检查是否已签署《ETF风险揭示书》，保证交易顺畅。谢谢！\n')
    f.write(f'其中跨境ETF513140由于极速柜台目前仍不支持RTGS实时交收，份额是T+1到账。如需进行跨境ETF套利，请注意持仓隔夜风险。\n')
    print('输出数据完毕')


